package com.example.schoolmanage.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.schoolmanage.domain.Role;
import com.example.schoolmanage.domain.User;
import com.example.schoolmanage.mapper.RoleMapper;
import com.example.schoolmanage.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：阿远
 * 描述：no bug
 */


@Component
public class SecurityUserService implements UserDetailsService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;
    //重写接口方法
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //当用户登录的时候，springsecurity就会将请求转发到此
        //根据用户名查找用户，不存在就抛出异常，存在就将用户名，密码，授权列表 组装成springsecurity的user对象 并返回
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username).last("limit 1");
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //定义权限列表
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        //给权限列表赋值
        List<Role>roleList = roleMapper.findRoleListByUserId(user.getUserId());
        for(Role role : roleList){
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleKeyword()));
        }

        UserDetails userDetails =
                new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
        //剩下的认证就由框架帮助我们完成
        return userDetails;
    }
}
